import React from 'react';

import { Card, Button, Space, Input, Form, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';

import LinkButton from '../../../components/LinkButton';
import ImgUpload from './ImgUpload';
import ChooseCategory from './ChooseCategory';
import RichTextEditor from './RichTextEditor';

import { reqUpdateProduct, reqAddProduct } from '../../../api';
import memory from '../../../utils/memoryUtils';

import './index.less';

const { Item, useForm } = Form;
const { TextArea } = Input;

export default function AddOrUpdate(props) {
    const { history } = props;

    const product = props.location.state.product || {};

    const isUpdate = !!product._id;

    const [form] = useForm();
    const editor = React.createRef('');

    return (
        <Card
            title={
                <Space className="product-add-header">
                    <LinkButton onClick={() => history.push('/product')}><ArrowLeftOutlined className="product-detail-header-icon" /></LinkButton>
                    <h2>{isUpdate ? '修改商品' : '添加商品'}</h2>
                </Space>
            }
            className="product-add"
        >
            <Form className="product-add-form" form={form} onFinish={() => submit(form, product, editor, history)}>
                <Item
                    label="商品名称"
                    name="name"
                    initialValue={product.name}
                    rules={[{ required: true, message: '商品名不能为空！' }]}
                >
                    <Input placeholder="商品名称" className="input" autoComplete="off"></Input>

                </Item>
                <Item
                    label="商品描述"
                    name="desc"
                    initialValue={product.desc}
                    rules={[{ required: true, message: '商品描述不能为空！' }]}
                >
                    <TextArea placeholder="商品描述" autoSize={{ minRows: 1, maxRows: 5 }} className="input" autoComplete="off"></TextArea>
                </Item>
                <Item
                    label="商品价格"
                    name="price"
                    initialValue={product.price}
                    rules={[{ required: true, validator: validatePrice }]}
                >
                    <Input type="number" addonAfter="元" className="input" autoComplete="off" />
                </Item>

                <Item
                    label="商品分类"
                    name="categoryIds"
                    rules={[{ required: true, message: '请选择商品分类！' }]}
                >
                    <ChooseCategory
                        categoryIds={isUpdate ? { pCategoryId: product.pCategoryId || '0', categoryId: product.categoryId } : {}}
                        setFieldsValue={(vals) => form.setFieldsValue(vals)}
                    />
                </Item>
                <Item
                    label="&nbsp;&nbsp;&nbsp;商品图片"
                    name="imgs"
                >
                    <ImgUpload
                        product={product}
                        setFieldsValue={(vals) => form.setFieldsValue(vals)}
                    />
                </Item>

                <Item
                    label="&nbsp;&nbsp;&nbsp;商品详情"
                    initialValue={product.detail}
                    name="detail"
                >
                    <RichTextEditor ref={editor} product={product}/>
                </Item>

                <Item name="submit" >
                    <Button type="primary" htmlType="submit">提交</Button>
                </Item>
            </Form>
        </Card>
    )
}

async function submit(form, product, editor, history) {
    const vals = form.getFieldsValue();
    if (vals.categoryIds.length === 1) {
        vals.categoryId = vals.categoryIds[0];
        vals.pCategoryId = '0';
    } else {
        [vals.pCategoryId, vals.categoryId] = vals.categoryIds;
    }
    delete vals.categoryIds;

    vals.detail = editor.current.getDetail();

    let res = null;
    if (product && product._id) {
        vals._id = product._id;
        vals.status = product.status;
        res = await reqUpdateProduct(vals);
        memory.productPageState = null;
    } else {
        vals.status = '2';
        res = await reqAddProduct(vals);
        memory.productPageState = null;
        history.push('/product');
    }
    if (res.status === 0) {
        message.success('操作成功！');
    } else {
        message.error('操作失败！');
    }
}

function validatePrice(_, val) {

    if (!val) {
        return Promise.reject('请输入商品价格');
    }

    if (+val < 0) {
        return Promise.reject('商品价格不能为负值！');
    }

    return Promise.resolve(val);
}